package com.csu.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.List;


/**
 * Class Name : ThmsWebSocketHandler<br/>
 * Description: Thms 系统的WebSocket处理器<br/>
 * 
 * @Version V1.0.0
 * @since JDK 1.7
 * 
 *        Date : 2017年12月7日<br/>
 * @author lds
 *
 */
public class ThmsWebSocketHandler implements WebSocketHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * thmsWebSocketHandler : 处理器<br/>
	 * 
	 * @since JDK 1.7
	 *
	 */
	private static ThmsWebSocketHandler thmsWebSocketHandler = null;

	public static ThmsWebSocketHandler getSystemWebSocketHandler() {
		thmsWebSocketHandler = null == thmsWebSocketHandler ? new ThmsWebSocketHandler() : thmsWebSocketHandler;
		return thmsWebSocketHandler;
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String userKey = session.getAttributes().get("userKey").toString();
		String userType = session.getAttributes().get("userType").toString();
		if (!StringUtils.isBlank(userKey) && !StringUtils.isBlank(userType)) {
			ThmsWebSocketUserMap.addUser(userKey,userType,session);
			if (logger.isDebugEnabled()) {
				logger.debug("用户" + userKey + "上线，成功建立连接。");
			}
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("参数错误，连接失败");
			}
		}
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("消息接收成功");
		}

	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
		}

	}

	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		String userKey = session.getAttributes().get("userKey").toString();
		String userType = session.getAttributes().get("userType").toString();
		if (!StringUtils.isBlank(userKey) && !StringUtils.isBlank(userType)) {
			ThmsWebSocketUserMap.removeUser(userType, userKey);
			if (logger.isDebugEnabled()) {
				logger.debug("用户" + userKey + "下线，断开连接。");
			}
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("参数错误，断开连接失败");
			}
		}
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}

	/**
	 * * 给指定在线用户发送消息
	 * 
	 * @param userKey
	 * @param message
	 */
	public void sendMessageToUser(ThmsWebSocketMessage message) {
		WebSocketSession user = ThmsWebSocketUserMap.getUserSession(message.getUserType(), message.getUserKey());
		if (null != user && user.isOpen()) {
			try {
				user.sendMessage(new TextMessage(JSON.toJSONString(message)));
				if (logger.isDebugEnabled()) {
					logger.debug("向用户" +  message.getUserKey() + "发送消息成功。");
				}
			} catch (IOException e) {
				if (logger.isDebugEnabled()) {
					logger.debug("向用户" +  message.getUserKey() + "发送消息失败。");
				}
			}
		}
	}


	/**
	 * 给家庭成员发送消息
	 *
	 * @param message
	 */
	public void sendMessageToUserFamily(ThmsWebSocketMessage message) {
		List<WebSocketSession> webSocketSessions = ThmsWebSocketUserMap.getWebSocketSessions(message.getUserType());
		if(null==webSocketSessions) {
			if (logger.isDebugEnabled()) {
				logger.debug("群发家庭成员消息失败。");
			}
			return ;
		}
		for (WebSocketSession user : webSocketSessions) {
			if (null != user && user.isOpen()) {
				try {
					user.sendMessage(new TextMessage(JSON.toJSONString(message)));
					if (logger.isDebugEnabled()) {
						logger.debug("向全体在线家庭成员发送消息成功。");
					}
				} catch (IOException e) {
					if (logger.isDebugEnabled()) {
						logger.debug("向全体在线家庭成员发送消息失败。");
					}
				}
			}
		}
	}



	/**
	 * 给所有在线用户发送消息
	 *
	 * @param message
	 */
	public void sendMessageToUsers(ThmsWebSocketMessage message) {
		List<WebSocketSession> webSocketSessions = ThmsWebSocketUserMap.getWebSocketSessions(message.getUserType());
		if(null==webSocketSessions) {
			if (logger.isDebugEnabled()) {
				logger.debug("群发消息失败。");
			}
			return ;
		}
		for (WebSocketSession user : webSocketSessions) {
			if (null != user && user.isOpen()) {
				try {
					user.sendMessage(new TextMessage(JSON.toJSONString(message)));
					if (logger.isDebugEnabled()) {
						logger.debug("向全体在线用户发送消息成功。");
					}
				} catch (IOException e) {
					if (logger.isDebugEnabled()) {
						logger.debug("向全体在线用户发送消息失败。");
					}
				}
			}
		}
	}




	/**
	 * 给所有在线用户发送消息
	 * 
	 * @param message
	 */
	public void sendMessageToUsersByPrefix(ThmsWebSocketMessage message,String prefix) {
		List<WebSocketSession> webSocketSessions = ThmsWebSocketUserMap.getWebSocketSessions(message.getUserType(),prefix);
		if(null==webSocketSessions) {
			if (logger.isDebugEnabled()) {
				logger.debug("群发消息失败。");
			}
			return ;
		}
		for (WebSocketSession user : webSocketSessions) {
			if (null != user && user.isOpen()) {
				try {
					user.sendMessage(new TextMessage(JSON.toJSONString(message)));
					if (logger.isDebugEnabled()) {
						logger.debug("向全体在线用户发送消息成功。");
					}
				} catch (IOException e) {
					if (logger.isDebugEnabled()) {
						logger.debug("向全体在线用户发送消息失败。");
					}
				}
			}
		}
	}

}